export default class SocketService {
  // 单例
  static instance = null;
  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService();
    }
    return this.instance;
  }
  // 和服务端连接的socket对象
  ws = null;
  // 函调函数集合
  callBackMapping = {};
  // 标识是否连接成功
  connected = false;
  // 记录重试的次数
  sendRetryCount = 0;
  // 重新连接尝试的次数
  connectRetryCount = 0;

  // 连接
  connect() {
    // 连接服务器
    if (!window.WebSocket) {
      return console.log('您的浏览器不支持WebSocket');
    }
    this.ws = new WebSocket('ws://localhost:9998');
    this.ws.onopen = () => {
      console.log('连接服务端成功了');
      this.connected = true;

      this.connectRetryCount = 0;
    };

    this.ws.onclose = () => {
      console.log('连接服务端失败');
      this.connected = false;
      this.connectRetryCount++;
      setTimeout(() => {
        this.connect()
      }, 500 * this.connectRetryCount)
    };

    this.ws.onmessage = (msg) => {
      console.log('从服务端获取到了数据');
      console.log('msg => ', msg);
      const receive = JSON.parse(msg.data);
      const socketType = receive.socketType;
      if (this.callBackMapping[socketType]) {
        const action = receive.action;
        if (action === 'getData') {
          const realData = JSON.parse(receive.data);
          this.callBackMapping[socketType].call(this, realData);
        } else if (action === 'fullScreen') {
          this.callBackMapping[socketType].call(this, receive)
        } else if (action === 'themeChange') {
          this.callBackMapping[socketType].call(this, receive)
        }
      }
    };
  }

  registerCallBack(socketType, callback) {
    this.callBackMapping[socketType] = callback;
  }

  unRegisterCallBack(socketType) {
    delete this.callBackMapping[socketType];
  }

  send(data) {
    if (this.connected) {
      this.sendRetryCount = 0;
      this.ws.send(JSON.stringify(data));
    } else {
      this.sendRetryCount++;
      setTimeout(() => {
        this.send(data);
      }, this.sendRetryCount * 500);
    }
  }
}
